<template>
  <div class="app-container">
	  <el-dialog v-model="dialogVisible" title="采购商品管理" width="90%" @closed="baseClosed" destroy-on-close :close-on-click-modal="false">
			<div id="printArea">
				<el-descriptions title="采购信息" size="small" border :column="4">
					<template #extra>
						<el-dropdown class="printBtn"  size="default" split-button type="primary">
						  <p v-print="printObj">打印</p>
						  <template #dropdown>
							<el-dropdown-menu>
							  <el-dropdown-item icon="CircleCheckFilled" style="color: #409EFF;" v-if="purchaseOrderInfo.status==1" @click="handleDownOrder" v-hasPermi="['crm:purchaseOrder:edit']">采购下单</el-dropdown-item>
							  <el-dropdown-item icon="CircleCheckFilled" style="color: #409EFF;" v-if="purchaseOrderInfo.status==2" @click="setStatusAuditor" v-hasPermi="['crm:purchaseOrder:edit']">审批通过</el-dropdown-item>
							  <el-dropdown-item icon="CircleCheckFilled" style="color: #409EFF;" v-if="purchaseOrderInfo.status==3" @click="open=true" v-hasPermi="['crm:purchaseOrder:edit']">验收货单</el-dropdown-item>
							  <el-dropdown-item icon="CircleCheckFilled" style="color: #E6A23C;" v-if="purchaseOrderInfo.status==4" @click="handleOpenInventory" v-hasPermi="['crm:purchaseOrder:edit']">货单入库</el-dropdown-item>
							  <el-dropdown-item icon="WarningFilled" v-if="purchaseOrderInfo.status==2" @click="setStatusRevoke" v-hasPermi="['crm:purchaseOrder:edit']">撤回修改</el-dropdown-item>
							  <el-dropdown-item :divided="true" style="color: #F56C6C;" icon="CircleCloseFilled" :disabled="purchaseOrderInfo.status==5||purchaseOrderInfo.status==0" @click="setZfStatus">作废</el-dropdown-item>
							</el-dropdown-menu>
						  </template>
						</el-dropdown>
					</template>
					<el-descriptions-item label="ID">{{purchaseOrderInfo.id}}</el-descriptions-item>
					<el-descriptions-item label="名称">{{purchaseOrderInfo.name}}</el-descriptions-item>
					<el-descriptions-item label="供应商">{{purchaseOrderInfo.text.supplier}}</el-descriptions-item>
					<el-descriptions-item label="下单门店">{{purchaseOrderInfo.belDeptId}}</el-descriptions-item>
					
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=2" label="下单人">{{purchaseOrderInfo.downBy}}</el-descriptions-item>
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=2" label="下单时间">{{purchaseOrderInfo.downTime}}</el-descriptions-item>
					
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=3" label="审核员">{{purchaseOrderInfo.auditorBy}}</el-descriptions-item>
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=3" label="审核时间">{{purchaseOrderInfo.auditorTime}}</el-descriptions-item>
					
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=4" label="验收人">{{purchaseOrderInfo.accepterBy}}</el-descriptions-item>
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=4" label="验收时间">{{purchaseOrderInfo.accepterTime}}</el-descriptions-item>
					
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=5" label="入库人">{{purchaseOrderInfo.putStoreBy}}</el-descriptions-item>
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=5" label="入库时间">{{purchaseOrderInfo.putStoreTime}}</el-descriptions-item>
					
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=2" label="进货总量">{{purchaseOrderInfo.total}}</el-descriptions-item>
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=2" label="赠送总量">{{purchaseOrderInfo.donate}}</el-descriptions-item>
					<el-descriptions-item v-if="parseInt(purchaseOrderInfo.status)>=2" label="进货总价">{{purchaseOrderInfo.amount}}</el-descriptions-item>
					
					<el-descriptions-item v-if="purchaseOrderInfo.status=='5'" label="实际进货总量">{{purchaseOrderInfo.realityTotal}}</el-descriptions-item>
					<el-descriptions-item v-if="purchaseOrderInfo.status=='5'" label="实际赠送总量">{{purchaseOrderInfo.realityDonate}}</el-descriptions-item>
					<el-descriptions-item v-if="purchaseOrderInfo.status=='5'" label="实际进货总价">{{purchaseOrderInfo.realityAmount}}</el-descriptions-item>
					
					<el-descriptions-item label="状态">{{purchaseOrderInfo.text.status}}</el-descriptions-item>
					<el-descriptions-item label="备注">{{purchaseOrderInfo.remark}}</el-descriptions-item>
			 </el-descriptions>

			<el-table v-loading="loading" :data="purchaseGoodsList" 
			class="printTable"
			border  
			:span-method="arraySpanMethod"
			size="small"
			style="height: calc(100vh - 380px);"
			>
			  <!-- <el-table-column type="selection" width="55" align="center" /> -->
			  <el-table-column type="index" align="center" label="序号" width="55" fixed="left"/>
			  <el-table-column label="商品概要" fixed="left">
				  <el-table-column label="名称|商品码" align="center" prop="goodsName" width="280" >
						<template #default="scope">
							<div v-if="scope.row.isAdd" style="text-align: left;">
								<selectGoods lable="输入搜索商品信息:" @selectChange="goodsSelectChange"/>
							</div>
							<div v-else>
								<span>{{scope.row.goodsName}}</span>|<span>{{scope.row.goodsCode}}</span>
							</div>
						</template>
				  </el-table-column>
				  <el-table-column label="商品类型" sortable align="center" prop="goodsType" width="120">
					<template #default="scope">
					  <dict-tag :options="bus_goods_type" :value="scope.row.goodsType"/>
					</template>
				  </el-table-column>
			  </el-table-column>
			  <el-table-column label="商品信息">
				  <el-table-column label="库存" align="center" prop="inventory" />
				  <el-table-column label="货号" align="center" prop="goodsNo" />
				  <el-table-column label="规格" align="center" prop="norms" />
			  </el-table-column>
			  <el-table-column label="进货信息">
				  <el-table-column label="进货量" align="center" prop="total" width="120">
					  <template #default="scope">
						  <el-input v-model="scope.row.total" :disabled="purchaseOrderInfo.status!=1" @change="(val)=>tableChange(val,scope.row,'total')" @input="(val)=>tableInput(val,scope.row,'total')" style="width: 90px" min="0" type="number"  placeholder="请输入进货量" />
					  </template>
				  </el-table-column>
				  <el-table-column label="赠送量" align="center" prop="donate" width="120">
					  <template #default="scope">
						  <el-input v-model="scope.row.donate" :disabled="purchaseOrderInfo.status!=1" @change="(val)=>tableChange(val,scope.row,'donate')" @input="(val)=>tableInput(val,scope.row,'donate')" style="width: 90px" min="0" type="number"  placeholder="请输入赠送量" />
					  </template>
				  </el-table-column>
				  <el-table-column label="销售价" align="center" prop="salePrice" />
				  <el-table-column label="进货价" align="center" prop="purchasePrice" width="190">
					  <template #default="scope">
						  <el-input v-model="scope.row.purchasePrice" :disabled="purchaseOrderInfo.status!=1" @change="(val)=>tableChange(val,scope.row,'purchasePrice')" @input="(val)=>tableInput(val,scope.row,'purchasePrice')" type="number" min="0" style="width: 120px" placeholder="请输入进货价" />
					  </template>
				  </el-table-column> 
				  <el-table-column label="进货金额" align="center" prop="amount"/>
			  </el-table-column>
			  <el-table-column label="验货信息">
				  <el-table-column label="实际进货量" align="center" prop="realityTotal" width="120">
						<template #default="scope">
							<el-input v-model="scope.row.realityTotal" :disabled="purchaseOrderInfo.status!=3" @change="(val)=>tableChange(val,scope.row,'realityTotal')" @input="(val)=>tableInput(val,scope.row,'realityTotal')" style="width: 90px" min="0" type="number"  placeholder="请输入实际进货量" />
						</template>
				  </el-table-column>
				  <el-table-column label="实际赠送量" align="center" prop="realityDonate" width="120">
					  <template #default="scope">
						  <el-input v-model="scope.row.realityDonate" :disabled="purchaseOrderInfo.status!=3" @change="(val)=>tableChange(val,scope.row,'realityDonate')"  style="width: 90px" min="0" type="number"  placeholder="请输入实际赠送量" />
					  </template>
				  </el-table-column>
				  <el-table-column label="实际进货金额" align="center" prop="realityAmount" width="190">
					  <template #default="scope">
						  <el-input v-model="scope.row.realityAmount" :disabled="purchaseOrderInfo.status!=3" @change="(val)=>tableChange(val,scope.row,'realityAmount')" style="width: 120px" min="0" type="number"  placeholder="请输入实际进货金额" />
					  </template>
				  </el-table-column>
			  </el-table-column>
			 <!-- 
			  <el-table-column label="备注" align="center" prop="remark" /> -->
			  <el-table-column label="操作" v-if="purchaseOrderInfo.status=='1'" align="center" fixed="right" class-name="small-padding fixed-width">
				<template #default="scope">
				  <el-button link type="primary" v-if="purchaseOrderInfo.status==1" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['crm:purchaseGoods:remove']">删除</el-button>
				</template>
			  </el-table-column>
			</el-table>
		</div>
	</el-dialog>
    
    <el-dialog title="对比信息" v-model="open" width="80%" append-to-body @closed="checkItem=null">
      <el-table :data="purchaseGoodsList" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="55" />
		  <el-table-column label="商品类型" sortable align="center" prop="goodsType" width="120">
		    <template #default="scope">
		      <dict-tag :options="bus_goods_type" :value="scope.row.goodsType"/>
		    </template>
		  </el-table-column>
          <el-table-column  label="商品名称" width="220" prop="goodsName"/>
		  <el-table-column  label="商品规格"  prop="norms"/>
          <el-table-column label="进货量>>实际进货量" width="180">
			  <template #default="scope">
				  <span style="color: #79bbff;">{{scope.row.total}}</span><el-icon><DArrowRight /></el-icon><span style="color: #c45656;">{{scope.row.realityTotal}}</span>
			  </template>
		  </el-table-column>
		  <el-table-column label="赠送量>>实际赠送量" width="180">
			  <template #default="scope">
				  <span style="color: #79bbff;">{{scope.row.donate}}</span><el-icon><DArrowRight /></el-icon><span style="color: #c45656;">{{scope.row.realityDonate}}</span>
			  </template>
		  </el-table-column>
		  <el-table-column label="进货金额>>实际进货金额" width="180">
			  <template #default="scope">
				   <span style="color: #79bbff;">{{(scope.row.total*scope.row.purchasePrice).toFixed(2)}}</span><el-icon><DArrowRight /></el-icon><span style="color: #c45656;">{{(scope.row.realityTotal*scope.row.purchasePrice).toFixed(2)}}</span>
			  </template>
		  </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
			<label>关联盘点：</label>
		  <el-select
			  v-model="checkItem"
			  filterable
			  remote
			  reserve-keyword
			  placeholder="请输入盘点ID|名称"
			  clearable 
			  remote-show-suffix
			  :remote-method="remoteCheckListMethod"
			  :loading="loading"
			  style="width: 240px"
			>
			  <el-option
				v-for="item in checkList"
				:key="item.id"
				:label="item.planName"
				:value="item.id"
			  />
			</el-select>
			&emsp13;
          <el-button type="primary" @click="setStatusAccept(1)">收货数量相符</el-button>
		  <el-button type="warning" @click="setStatusAccept(2)">直接收货</el-button>
          <el-button @click="open=false">继续调整</el-button>
        </div>
      </template>
    </el-dialog>
	
	
	<el-dialog title="库存信息" v-model="inventoryOpen" width="80%"  append-to-body>
	  <el-table :data="inventoryList" stripe style="width: 100%">
	      <el-table-column type="index" label="序号" width="55" />
		  <el-table-column label="商品类型" sortable align="center" prop="goodsType" width="120">
		    <template #default="scope">
		      <dict-tag :options="bus_goods_type" :value="scope.row.goodsType"/>
		    </template>
		  </el-table-column>
	      <el-table-column  label="商品名称" width="220" prop="goodsName"/>
		  <el-table-column  label="商品规格"  prop="norms"/>
	      <el-table-column label="商品库存" width="180" prop="currentInventory"/>
		  <el-table-column label="采购单数量" width="180" prop="realityTotal"/>
		  <el-table-column label="同步结果" width="180">
			  <template #default="scope">
				   <span style="color: #79bbff;">{{scope.row.currentInventory}}+{{scope.row.realityTotal}}=</span><span style="color: #c45656;">{{scope.row.currentInventory+scope.row.realityTotal}}</span>
			  </template>
		  </el-table-column>
	  </el-table>
	  <template #footer>
	    <div class="dialog-footer">
	      <el-button type="primary" @click="setSyncInventory">同步库存</el-button>
	      <el-button @click="inventoryOpen=false">取  消</el-button>
	    </div>
	  </template>
	</el-dialog>
	
  </div>
</template>

<script setup name="PurchaseGoods">
import { listByPurchase, savePurchaseGoods,loadListRelInventory,syncInventory,addPurchaseGoods,updatePurchaseGoods,delPurchaseGoods } from "@/api/crm/purchaseGoods";
import {  getPurchaseOrder,setDownOrder,setPurchaseOrderStatus,setCheckAuditor,setCheckAccept } from "@/api/crm/purchaseOrder";
import { queryCheckPlan } from "@/api/crm/checkPlan";
import selectGoods from '../goods/select.vue';



import { queryGoodsInfo } from "@/api/crm/goodsInfo";
import { onMounted, ref } from "vue";

const { proxy } = getCurrentInstance();
const { bus_goods_type } = proxy.useDict('bus_goods_type');


const route = useRoute();

const purchaseGoodsList = ref([]);

const purchaseOrderInfo = ref(null)

const dialogVisible = ref(false);

const open = ref(false);

const inventoryOpen = ref(false);
const inventoryList = ref([]);

const loading = ref(true);
const showSearch = ref(true);

const checkList = ref([])
const checkItem = ref(null)


const printObj = ref({
	id:'printArea',
	popTitle:'春野美妆采购单',
	preview:true,
	extraCss:new URL('../../../assets/styles/print.css', import.meta.url).href,
	previewBeforeOpenCallback(){
		console.log('预览工具打开前')
	}
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    purchaseOrderId: null,
    goodsId: null,
    goodsName: null,
    goodsCode: null,
    goodsType: null,
    goodsNo: null,
    norms: null,
    total: null,
    donate: null,
    salePrice: null,
    purchasePrice: null,
    amount: null,
    realityTotal: null,
    realityDonate: null,
    realityAmount: null,
  },
  defaultItem:{
	isAdd:true,
	purchaseOrderId: null,
	goodsId: null,
	goodsName: null,
	goodsCode: null,
	goodsType: '-',
	goodsNo: '-',
	inventory: 0,
	norms: null,
	total: 0,
	donate: 0,
	salePrice: 0,
	purchasePrice: 0,
	amount: 0,
	realityTotal: null,
	realityDonate: null,
	realityAmount: null,
  },
  rules: {
  }
});

const { queryParams, form, rules,defaultItem } = toRefs(data);

const emit = defineEmits(['closed'])

function openWin(purchaseId){
	
	queryParams.value.purchaseOrderId = purchaseId;
	
	setPurchaseOrderInfo(queryParams.value.purchaseOrderId).then(rsp=>{
		dialogVisible.value = true;
		purchaseOrderInfo.value = rsp.data;
		getList();
	})
}
/** 查询采购货品列表 */
function getList() {
  loading.value = true;
  listByPurchase(queryParams.value.purchaseOrderId).then(response => {
    purchaseGoodsList.value = response.data;
    loading.value = false;
	//
	if(purchaseOrderInfo.value.status=="1"){
		purchaseGoodsList.value.push(defaultItem.value)
	}
	
  });
}

function setPurchaseOrderInfo(id){
	return getPurchaseOrder(id)
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


function tableInput(value,row,type){
	//修改进货量
	if('total'==type){
		row.amount = (row.purchasePrice*row.total).toFixed(2);
		
		row.realityTotal = row.total;
		row.realityAmount = (row.realityTotal*row.purchasePrice).toFixed(2);
	}
	//修改赠送量
	if('donate'==type){
		row.realityDonate = value
	}
	//修改进货价
	if('purchasePrice'==type){
		row.amount = (row.purchasePrice*row.total).toFixed(2)
		row.realityAmount = (row.realityTotal*row.purchasePrice).toFixed(2);
	}
	
	//修改实际进货量
	if('realityTotal'==type){
		row.realityAmount = row.realityTotal*row.purchasePrice
	}
}

function tableChange(value,row,type){
	//console.log(value,row,type)
	updatePurchaseGoods(row).then(rsp=>{
		
	})
}



function arraySpanMethod(params){
	
	if(true==params.row.isAdd){
		
		if(params.columnIndex==1){
			return [1, 9]
		}
		return [0,0]
	}
	return [1,1]
}

/** 新增按钮操作 */
function handleSave() {
	
	const array =  [];
	for (var i = 0; i < purchaseGoodsList.value.length; i++) {
		if(!purchaseGoodsList.value[i].isAdd){
			array.push(Object.assign({},purchaseGoodsList.value[i]))
		}
	}
	
	savePurchaseGoods(array,queryParams.value.purchaseOrderId).then(rsp=>{
		getList();
		proxy.$modal.msgSuccess("保存成功");
	})
}



/** 删除按钮操作 */
function handleDelete(row) {
	const _ids = row.id;
	proxy.$modal.confirm('是否确认删除采购商品编号为"' + _ids + '"的数据项？').then(function() {
	  return delPurchaseGoods(_ids);
	}).then(() => {
	  getList();
	  proxy.$modal.msgSuccess("删除成功");
	}).catch(() => {});

}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('crm/purchaseGoods/export', {
    ...queryParams.value
  }, `purchaseGoods_${new Date().getTime()}.xlsx`)
}

/** 返回按钮操作 */
function handleClose() {
	dialogVisible.value = false;
}

//打开同步窗口
function handleOpenInventory(){
	
	loadListRelInventory(queryParams.value.purchaseOrderId).then(rsp=>{
		inventoryList.value = rsp.data
		inventoryOpen.value = true;
	})
	
}

function remoteCheckListMethod(query){
	queryCheckPlan({value:query}).then(rsp=>{
		checkList.value = rsp.rows;
	})
}
//商品选择后
function goodsSelectChange(item){
	console.log('选中的产品是',item)
	
	//检测是否已添加
	for (var i = 0; i < purchaseGoodsList.value.length; i++) {
		if(purchaseGoodsList.value[i].goodsId==item.id){
			proxy.$modal.msgWarning('该商品已添加.')
			return false;
		}
	}
	
	const tempItem = {
		purchaseOrderId: queryParams.value.purchaseOrderId,
		goodsId: item.id,
		goodsName: item.goodsName,
		goodsCode: item.goodsCode,
		goodsType: item.goodsType,
		goodsNo: item.goodsNo,
		inventory:item.inventory,
		norms: item.norms,
		total: 1,
		donate: 0,
		salePrice: item.salePrice,
		purchasePrice: item.purchasePrice,
		amount: item.purchasePrice*1,
		realityTotal: 1,
		realityDonate: 0,
		realityAmount: null,
		remark: null,
	}
	
	addPurchaseGoods(tempItem).then(rsp=>{
		purchaseGoodsList.value.splice(purchaseGoodsList.value.length-1,0,rsp.data);
	})
	
}


//下单
function handleDownOrder(){
	
	proxy.$modal.confirmTitle('确定下单吗？',"下单提示").then(function() {
	  return setDownOrder(queryParams.value.purchaseOrderId);
	}).then(() => {
	  proxy.$modal.msgSuccess("下单成功");
	  handleClose(); 
	}).catch(() => {});
	
}

function setStatus(status){
	return setPurchaseOrderStatus({'id':queryParams.value.purchaseOrderId,'status':status});
}

function setZfStatus(){
	proxy.$modal.confirmTitle('是否确认作废该采购单？',"采购单提示").then(function() {
	  return setStatus('0');
	}).then(() => {
	  proxy.$modal.msgSuccess("作废成功");
	  handleClose();
	}).catch(() => {});
	
}

function setStatusRevoke(){
	proxy.$modal.confirmTitle('是否撤回修改该采购单？',"采购单提示").then(function() {
	  return setStatus('1');
	}).then(() => {
	  proxy.$modal.msgSuccess("撤回修改成功");
	  handleClose();
	}).catch(() => {});
}

//审批
function setStatusAuditor(){
	proxy.$modal.confirmTitle('是否审批通过该采购单？',"采购单提示").then(function() {
		return setCheckAuditor(queryParams.value.purchaseOrderId);
	}).then(() => {
	  proxy.$modal.msgSuccess("审批通过成功");
	  handleClose();
	}).catch(() => {});
}


//验收
function setStatusAccept(index){
	
	var subData = {'id':queryParams.value.purchaseOrderId,'list':[]}
	for (var i = 0; i < purchaseGoodsList.value.length; i++) {
		const item = purchaseGoodsList.value[i]
		
		subData.list.push({'id':item.id,'realityTotal':item.realityTotal,'realityDonate':item.realityDonate,'realityAmount':item.realityAmount,"goodsId":item.goodsId})
	}
	
	
	if(index==1){
		if(checkItem.value==null){
			proxy.$modal.msgWarning("请关联盘点信息");
			return;
		}
		
		subData.checkPlanId = checkItem.value
		setCheckAccept(subData).then(rsp=>{
			proxy.$modal.msgSuccess("验收成功");
			open.value = false;
			handleClose();
		})
	}else{
		proxy.$modal.confirmTitle('确定不进行盘点校验直接验收成功该条记录？',"验收提示").then(function() {
			return setCheckAccept(subData);
		}).then(() => {
		  proxy.$modal.msgSuccess("验收成功");
		  open.value = false;
		  handleClose();
		}).catch(() => {});
	}
	
	
}

//同步库存
function setSyncInventory(){
	syncInventory(queryParams.value.purchaseOrderId).then(rsp=>{
		proxy.$modal.msgSuccess("库存同步");
		inventoryOpen.value = false;
		handleClose();
	})
}
function baseClosed(){
	 emit('closed')
}


defineExpose({
	openWin
})

</script>